package xyz.bmj.view;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import xyz.bmj.model.HotKeySetting;
import xyz.bmj.util.Constant;

import java.io.File;
import java.nio.charset.StandardCharsets;

public class MainView extends Application {

    public static Stage mainStage;
    public static Controller mainCtr;
    public static Parent root;
    private Parent setting;
    public static Scene mainScene;
    public static HotKeySetting hks;

    @Override
    public void start(Stage primaryStage) throws Exception {
        hks = JSONUtil.readJSON(new File(getClass().getResource(Constant.SETTING_PATH).getPath()), StandardCharsets.UTF_8)
                .toBean(HotKeySetting.class);
        mainStage = primaryStage;
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/sample.fxml"));
        VBox root = loader.load();
        mainCtr = loader.getController();
        this.setting = FXMLLoader.<VBox>load(getClass().getResource("/setting.fxml"));
        MainView.root = root;
        primaryStage.setTitle("Hello World");
        Scene mainScene = new Scene(root, 800, 600);
        MainView.mainScene = mainScene;
        primaryStage.setScene(mainScene);
        primaryStage.show();

        MenuBar menuBar = initMenu(primaryStage);
        root.getChildren().add(0, menuBar);


    }

    private MenuBar initMenu(Stage primaryStage) {
        MenuBar menuBar = new MenuBar();
        Menu settingMenu = new Menu("设置");
        MenuItem hkSetting = new MenuItem("快捷键设置");
        hkSetting.setOnAction(event -> {
            mainScene.setRoot(setting);
        });
        MenuItem downloadAll = new MenuItem("download all");
        downloadAll.setOnAction(event -> {
            ThreadUtil.execAsync(() -> mainCtr.downloadAll());
        });

        settingMenu.getItems().addAll(hkSetting, downloadAll);
        menuBar.getMenus().addAll(settingMenu);
        return menuBar;
    }
}
